package com.hx.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Huathy
 * @date 2021-10-19 23:10
 * @description 同步阻塞IO模型
 */
public class BioServer {
    /**
     * 服务端网络IO模型的封装对象
     */
    ServerSocket server;

    /**
     * 服务器
     * @param port 端口
     */
    public BioServer(int port){
        try {
            server = new ServerSocket(port);
            System.out.println("BIO服务启动，端口：" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始监听
     */
    public void listen() throws IOException {
        //循环监听
        while (true){
            //等待客户端连接，阻塞方法
            //socket数据发送者在服务端的引用
            Socket client = server.accept();
            System.out.println(client.getInetAddress() + ":" +client.getPort());

            InputStream is = client.getInputStream();
            byte[] buff = new byte[1024];
            int len = is.read(buff);
            if(len > 0){
                String msg = new String(buff,0,len);
                System.out.printf("收到:[%s]\n",msg);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new BioServer(8888).listen();
    }
}
